package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.OrderDTO;
import com.example.vendingmachine.dto.OrderQuery;
import com.example.vendingmachine.dto.OrderStatsDTO;
import com.example.vendingmachine.entity.Order;
import com.example.vendingmachine.service.OrderService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 订单管理控制器
 */
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    /**
     * 分页查询订单列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('order:list')")
    public Result<PageInfo<Order>> list(OrderQuery query) {
        return Result.success(orderService.listOrders(query));
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('order:list')")
    public Result<Order> getInfo(@PathVariable Long id) {
        return Result.success(orderService.getOrderById(id));
    }

    /**
     * 根据订单编号获取订单
     */
    @GetMapping("/no/{orderNo}")
    @PreAuthorize("hasAuthority('order:list')")
    public Result<Order> getByOrderNo(@PathVariable String orderNo) {
        return Result.success(orderService.getOrderByOrderNo(orderNo));
    }

    /**
     * 创建订单
     */
    @PostMapping
    public Result<Order> create(@Validated @RequestBody OrderDTO orderDTO) {
        return Result.success(orderService.createOrder(orderDTO));
    }

    /**
     * 支付订单
     */
    @PutMapping("/{id}/pay")
    public Result<Void> pay(@PathVariable Long id) {
        orderService.payOrder(id);
        return Result.success();
    }

    /**
     * 完成订单
     */
    @PutMapping("/{id}/complete")
    @PreAuthorize("hasAuthority('order:edit')")
    public Result<Void> complete(@PathVariable Long id) {
        orderService.completeOrder(id);
        return Result.success();
    }

    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public Result<Void> cancel(@PathVariable Long id) {
        orderService.cancelOrder(id);
        return Result.success();
    }

    /**
     * 退款订单
     */
    @PutMapping("/{id}/refund")
    @PreAuthorize("hasAuthority('order:edit')")
    public Result<Void> refund(@PathVariable Long id) {
        orderService.refundOrder(id);
        return Result.success();
    }

    /**
     * 获取订单统计数据
     */
    @GetMapping("/stats")
    @PreAuthorize("hasAuthority('order:list')")
    public Result<OrderStatsDTO> getStats(OrderQuery query) {
        return Result.success(orderService.getOrderStats(query));
    }
} 